<template>
	<view class="warp">
		<uni-forms ref="form" :modelValue="formData" :rules="rules" label-width="80px" :border="true">
			<uni-group mode="card">
				<uni-list style="margin-bottom: 10px;">
					<uni-list-item class="item">
						<template v-slot:body>
							<view class="genderBox">
								<text>修改头像</text>
								<up-avatar width="30px" height="30px"></up-avatar>
							</view>
						</template>
					</uni-list-item>
					<uni-list-item class="item" @click="setNickname('')" title="昵称"
						:rightText="userInfo.nickname||'未设置'" link>
					</uni-list-item>
					<uni-list-item class="item" @click="bindMobile" title="手机号" :rightText="userInfo.mobile||'未绑定'"
						link>
					</uni-list-item>
					<uni-list-item class="item">
						<template v-slot:body>
							<view class="genderBox">
								<text>性别</text>
								<uni-data-checkbox :modelValue="gender" :localdata="localGender"
									@change="changeGender" />
							</view>
						</template>
					</uni-list-item>
				</uni-list>
				<uni-forms-item label="自我介绍" :name="['baseInfo','mydes']" :rules="[{'required': true,errorMessage: '自我介绍必填'}]" required>
					<uni-easyinput type="textarea" v-model="formData.baseInfo.mydes" placeholder="请输入内容"
						:inputBorder="false"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="图片" name="images" required>
					<uni-file-picker v-model="formData.images" limit="3" file-mediatype="image"></uni-file-picker>
					<!-- <uni-easyinput type="textarea" v-model="formData.i" placeholder="请输入内容"
						:inputBorder="false"></uni-easyinput> -->
				</uni-forms-item>
			</uni-group>
			<uni-group title="基本信息" margin-top="10" mode="card"> 
				<uni-forms-item label="年龄" :name="['baseInfo','age']" :rules="[{'required': true,errorMessage: '年龄必填'}]" required>
					<uni-easyinput placeholder="请输入内容" v-model.number="formData.baseInfo.age"
						:inputBorder="false"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="身高(cm)" :name="['baseInfo','height']" :rules="[{'required': true,errorMessage: '身高必填'}]" required>
					<uni-easyinput placeholder="请输入内容" v-model.number="formData.baseInfo.height"
						:inputBorder="false"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="学历" :name="['baseInfo','edu']" :rules="[{'required': true,errorMessage: '学历必选'}]" required>
					<uni-data-picker :localdata="edu" v-model="formData.baseInfo.edu" popup-title="请选择"
						:border="false"></uni-data-picker>
				</uni-forms-item>
				<!-- <uni-forms-item label="婚史" :name="['baseInfo','mar']" :rules="[{'required': true,errorMessage: '婚史必选'}]" required>
					<uni-data-picker :localdata="mar" v-model="formData.baseInfo.mar" popup-title="请选择"
						:border="false"></uni-data-picker>
				</uni-forms-item> -->
				<uni-forms-item label="婚史">
					<uni-data-picker :localdata="mar" v-model="formData.baseInfo.mar" popup-title="请选择"
						:border="false"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="月收入" :name="['baseInfo','inCome']" :rules="[{'required': true,errorMessage: '月收入必选'}]" required>
					<uni-data-picker :localdata="inCome" v-model="formData.baseInfo.inCome" popup-title="请选择"
						:border="false"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="所在城市" :name="['baseInfo','city']" :rules="[{'required': true,errorMessage: '所在城市必选'}]" required>
					<uni-data-picker placeholder="请选择地址" popup-title="请选择城市" collection="opendb-city-china"
						field="code as value, name as text" orderby="value asc" :step-searh="true" self-field="code"
						parent-field="parent_code" :value="city" @change="cityChange" :border="false"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="房车状况" :name="['baseInfo','house']" :rules="[{'required': true,errorMessage: '房车状况必选'}]" required>
					<uni-data-picker :localdata="house" v-model="formData.baseInfo.house" popup-title="请选择"
						:border="false"></uni-data-picker>
				</uni-forms-item>
			</uni-group>
			<uni-group title="详细资料" margin-top="10" mode="card">
				<uni-forms-item label="性格" :name="['baseInfo','nature']" :rules="[{'required': true,errorMessage: '性格必选'}]"  required>
					<uni-data-picker :localdata="localNature" v-model="formData.baseInfo.nature" popup-title="请选择"
						:border="false"></uni-data-picker>
				</uni-forms-item>

				<uni-forms-item label="血型" :name="['baseInfo','btype']" :rules="[{'required': true,errorMessage: '血型必选'}]"  required>
					<uni-data-picker :localdata="array" v-model="formData.baseInfo.btype" popup-title="请选择"
						:border="false"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="体态" :name="['baseInfo','bearing']" :rules="[{'required': true,errorMessage: '体态必选'}]" required>
					<uni-data-picker :localdata="localBearing" popup-title="体态" v-model="formData.baseInfo.bearing"
						placeholder="体态" :border="false" :clear-icon="false"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="属相" :name="['baseInfo','zodiac']" :rules="[{'required': true,errorMessage: '属相必选'}]" required>
					<uni-data-picker :localdata="localZodiac" popup-title="属相" v-model="formData.baseInfo.zodiac"
						placeholder="属相" :border="false" :clear-icon="false"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="职业" :name="['baseInfo','calling']" :rules="[{'required': true,errorMessage: '职业必选'}]" required>
					<uni-easyinput  v-model="formData.baseInfo.calling" placeholder="职业" :input-border="false"/>
					<!-- <uni-data-picker :localdata="localZodiac" popup-title="属相" v-model="formData.baseInfo.zodiac"
						placeholder="属相" :border="false" :clear-icon="false"></uni-data-picker> -->
				</uni-forms-item>
				<uni-forms-item label="婚后与父母同居" :name="['baseInfo','parents']" :rules="[{'required': true,errorMessage: '婚后与父母同居必选'}]" required>
					<uni-data-picker :localdata="beforMar" popup-title="婚后与父母同居" v-model="formData.baseInfo.parents"
						placeholder="" :border="false" :clear-icon="false"></uni-data-picker>
					<!-- <uni-easyinput placeholder="请输入内容" :inputBorder="false"></uni-easyinput> -->
				</uni-forms-item>
				<uni-forms-item label="婚前同居" :name="['baseInfo','beforMar']" :rules="[{'required': true,errorMessage: '婚前同居必选'}]" required>
					<uni-data-picker :localdata="beforMar" popup-title="婚前同居" v-model="formData.baseInfo.beforMar"
						placeholder="" :border="false" :clear-icon="false"></uni-data-picker>
				</uni-forms-item>
			</uni-group>
			<uni-group title="伴侣条件" margin-top="10" mode="card">
				<uni-forms-item label="所在地" :name="['seach','zCity']" :rules="[{'required': true,errorMessage: '所在地必选'}]" required>
					<uni-data-checkbox v-model="formData.seach.zCity" :localdata="localCity"></uni-data-checkbox>
				</uni-forms-item>
				<uni-forms-item label="年龄" :name="['seach','zAge']" :rules="[{'required': true,errorMessage: '年龄必选'}]" required>
					<uni-data-picker :localdata="[...ages,{value:'不限',text:'不限'}]" popup-title="请选择" v-model="formData.seach.zAge"
						:border="false"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="身高" :name="['seach','zHeight']" :rules="[{'required': true,errorMessage: '身高必选'}]" required>
					<uni-data-picker :localdata="[...pHeight,{value:'不限',text:'不限'}]" popup-title="请选择" v-model="formData.seach.zHeight"
						:border="false"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="最低学历" :name="['seach','zEdu']" :rules="[{'required': true,errorMessage: '最低学历必选'}]" required>
					<uni-data-picker :localdata="[...edu,{value:'不限',text:'不限'}]" popup-title="请选择" v-model="formData.seach.zEdu"
						:border="false"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="最低收入" :name="['seach','zInCome']" :rules="[{'required': true,errorMessage: '最低收入必选'}]" required>
					<uni-data-picker :localdata="[...inCome,{value:'不限',text:'不限'}]" popup-title="请选择" v-model="formData.seach.zInCome"
						:border="false"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="房车状况" :name="['seach','zHouse']" :rules="[{'required': true,errorMessage: '房车状况必选'}]" required>
					<uni-data-picker :localdata="[...house,{value:'不限',text:'不限'}]" v-model="formData.seach.zHouse" popup-title="请选择"
						:border="false"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="体态" :name="['seach','zBearing']" :rules="[{'required': true,errorMessage: '体态必选'}]" required>
					<uni-data-picker :localdata="[...localBearing,{value:'不限',text:'不限'}]" popup-title="体态" v-model="formData.seach.zBearing"
						placeholder="体态" :border="false" :clear-icon="false"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="属相" :name="['seach','zZodiac']" :rules="[{'required': true,errorMessage: '属相必选'}]" required>
					<uni-data-picker :localdata="[...localZodiac,{value:'不限',text:'不限'}]" popup-title="属相" v-model="formData.seach.zZodiac"
						placeholder="属相" :border="false" :clear-icon="false"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="性格" :name="['seach','zNature']" :rules="[{'required': true,errorMessage: '性格必选'}]" required>
					<uni-data-picker :localdata="[...localNature,{value:'不限',text:'不限'}]" v-model="formData.seach.zNature" popup-title="请选择"
						:border="false"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="婚史" :name="['seach','zMar']" :rules="[{'required': true,errorMessage: '婚史必选'}]" required>
					<uni-data-picker :localdata="[...mar,{value:'不限',text:'不限'}]" v-model="formData.seach.zMar" popup-title="请选择"
						:border="false"></uni-data-picker>
				</uni-forms-item>
			</uni-group>
		</uni-forms>
		<view class="btn">
			<button type="primary" size="mini" @click="onsubmit">提交</button>
		</view>

		<uni-popup ref="dialog" type="dialog">
			<uni-popup-dialog mode="input" :value="userInfo.nickname" @confirm="setNickname"
				:inputType="setNicknameIng?'nickname':'text'" title="设置昵称" placeholder="请输入要设置的昵称">
			</uni-popup-dialog>
		</uni-popup>
		<uni-id-pages-bind-mobile ref="bind-mobile-by-sms" @success="bindMobileSuccess"></uni-id-pages-bind-mobile>
	</view>
</template>

<script>
	import validator from './validator.js';
	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}
	import {
		useUserStore
	} from "@/pinia/user.js"
	import {
		mapState
	} from "pinia"
	const db = uniCloud.database();

	export default {
		data() {
			return {
				localGender: [{
					text: "男",
					value: 1
				}, {
					text: "女",
					value: 2
				}],
				formData: {
					baseInfo: {
						height: null,
						age: null,
						mydes: '',
						edu: null,
						mar: null,
						inCome: null,
						work: null,
						house: null, //房车
						city: null,
						btype: null,
						parents: null,
						beforMar: null,
						nature: null, //性格
						bearing: null, //体态
						zodiac: null, //属相 
						calling:null,//职业
					},
					seach: {
						zZodiac: null, //属相 
						zNature: null, //性格
						zBearing: null, //体态
						zHouse: null, //房车
						zMar: null, //婚姻
						zCity: 3, //城市
						zAge: null, //年龄
						zHeight: null, //身高
						zEdu: null, //学历
						zInCome: null //收入
					},
					images:[],//生活照片集合
				},
				rules: {
					...getValidator(["images"])
				},
				index: 0,
				city: [],
				array: [{
						value: 0,
						text: "A"
					}, {
						value: 1,
						text: "B"
					},
					{
						value: 2,
						text: "AB"
					},
					{
						value: 3,
						text: "O"
					}
				],
				beforMar: [{
						value: 0,
						text: "能"
					}, {
						value: 1,
						text: "不能"
					},
					{
						value: 2,
						text: "看情况"
					}
				],
				city:''
			}
		},
		async onLoad() {
			let res = await db.collection("uni-id-users").doc(this.userInfo._id).field('baseInfo,seach,images').get()
			if (res.result.data && res.result.data.length > 0) {
				this.formData = Object.assign(this.formData, res.result.data[0])
				delete this.formData._id
				if(this.formData.baseInfo.city && this.formData.baseInfo.city.length>0){
					this.city = this.formData.baseInfo.city[2].value
				}
				console.log("this.formData", this.formData)
			}
		},
		computed: {
			...mapState(useUserStore, ["sysSetting", 'userInfo', 'updateUserInfo']),
			gender() {
				return this.userInfo.gender || 0
			},
			isTo(){//设置比选
				return this.userInfo?.mobile && this.userInfo?.nickname && this.userInfo?.avatar_file && this.userInfo?.gender
			},
			ages() {
				return this.sysSetting.ages.map((item, index) => ({
					value: index,
					text: item
				}))
			},
			pHeight() {
				return this.sysSetting.pHeight.map((item, index) => ({
					value: index,
					text: item
				}))
			},
			edu() {
				return this.sysSetting.edu.map((item, index) => ({
					value: index,
					text: item
				}))
			},
			inCome() {
				return this.sysSetting.inCome.map((item, index) => ({
					value: index,
					text: item
				}))
			},
			//婚史
			mar() {
				return this.sysSetting.mar.map((item, index) => ({
					value: index,
					text: item
				}))
			},
			//房车
			house() {
				return this.sysSetting.house.map((item, index) => ({
					value: index,
					text: item
				}))
			},
			//地区
			localCity() {
				let local = ["本省", "本市", "本县", "不限"]
				return local.map((item, index) => ({
					value: index,
					text: item
				}))
			},
			//属相  
			localZodiac() {
				let local = ['鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪']
				return local.map((item, index) => ({
					value: index,
					text: item
				}))
			},
			//体态
			localBearing() {
				let local = ['偏瘦', '瘦', '微胖', '偏胖', '胖']
				return local.map((item, index) => ({
					value: index,
					text: item
				}))
			},
			//性格
			localNature() {
				let local = ['外向', '内向', '中间']
				return local.map((item, index) => ({
					value: index,
					text: item
				}))
			}
		},
		methods: {
			cityChange(e) {
				this.formData.baseInfo.city = e.detail.value
				this.formData.city = e.detail.value.map((item) => item.value)
				console.log(this.formData.baseInfo.city)
				// formData.city
			},
			setNickname(nickname) {
				if (nickname) {
					this.updateUserInfo({
						nickname
					})
					this.setNicknameIng = false
					this.$refs.dialog.close()
				} else {
					this.$refs.dialog.open()
				}
			},
			bindMobile() {
				this.$refs['bind-mobile-by-sms'].open()
			},
			bindMobileSuccess() {
				this.updateUserInfo()
			},
			changeGender(e) {
				let gender = e.detail.value
				this.updateUserInfo({
					gender
				})
			},
			titleCase: (str) => { //首字母大写
				let newStr = str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase();
				return newStr;
			},
			onsubmit(){
				if(!this.isTo){
					return uni.showModal({
						title:"提示",
						content:"手机,昵称,头像,性别必须要填写",
						showCancel:false
					})
				}
				// console.log("rules===>",this.rules);
				this.$refs.form.validate().then(res=>{
					this.submit()
				}).catch(e => {
					uni.showToast({
						title:"您还有必须要填写项目需要填写",
						icon:'none'
					})
				})
				return
			},
			submit() {
				let base = this.formData.baseInfo
				if(!base.age || !base.height){
					uni.showToast({
						title:"年龄与身高必须填写哦",
						icon:'none'
					})
					return
				}
				let cityCode = ''
				if (this.formData.seach.zCity != 3 && (this.formData.baseInfo.city == null || this.formData.baseInfo.city
						.length == 0)) {
					uni.showToast({
						title: "请选择所在城市",
						icon: 'none'
					})
					return
				} else {
					if (this.formData.seach.zCity != 3) {
						cityCode = this.formData.baseInfo.city[this.formData.seach.zCity].value
						console.log("city", cityCode)
					}
				}
				let str = ''
				// console.log("formData", this.formData)
				for (let key in base) {
					if (base[key] === null || base[key] === '') {
						continue
					}
					if (key == "age") {
						for (let i = 0; i < this.sysSetting.ages.length; i++) {
							let item = this.sysSetting.ages[i]
							let arr = item.split('-')
							if (base[key] >= arr[0] && base[key] < arr[1]) {
								str += `age${i}-`
								break;
							}
						}
					} else if (key == "height") {
						for (let i = 0; i < this.sysSetting.pHeight.length; i++) {
							let item = this.sysSetting.pHeight[i]
							// console.log(item)
							if (item.indexOf("以上") != -1) {
								str += `pHeight${i}-`
								break;
							}
							let arr = item.split('-')
							// console.log("arr", arr, base[key], i)
							if (base[key] >= arr[0] && base[key] < arr[1]) {
								str += `pHeight${i}-`
								break;
							}
						}
					} else if (key == "city") {
						if (base[key].length == 0) {
							continue
						}
						for (let i = 0; i < base[key].length; i++) {
							str += `zCity${base[key][i].value}-`
						}
					} else {
						// console.log("k", key)
						str += 'z' + this.titleCase(key) + base[key] + '-'
					}
				}
				this.formData.str = str
				// console.log("str", str)
				// console.log("cityCode", cityCode)
				let seach = this.formData.seach
				let seachStr = ''
				let seachArr = []
				for (let k in seach) {
					// console.log("++++",seach[k])
					if (seach[k] === null || seach[k] === '' || seach[k] == '不限') {
						continue
					}
					seachArr.push(seach[k])
					
					if (k == "zCity") {
						if (cityCode) {
							seachStr += `zCity${cityCode}`
						}
						continue
					}
					if (k == "zAge") {
						seachStr += `age${seach[k]}|`
						continue
					}
					if (k == "zHeight") {
						seachStr += `pHeight${seach[k]}|`
						continue
					}
					if (k == "zEdu") {
						for (let i = seach[k]; i < this.sysSetting.edu.length; i++) {
							seachStr += `zEdu${i}|`
						}
						continue
					}
					if (k == "zInCome") {
						for (let i = seach[k]; i < this.sysSetting.inCome.length; i++) {
							seachStr += `zInCome${i}|`
						}
						continue
					}
					seachStr += `${k}${seach[k]}|`
				}
				// console.log("+++++++",seachArr)
				// return
				// console.log("seachStr", seachStr,seachArr)
				if (seachStr) {
					// zCity zAge zHeight zEdu zInCome
					let len = seachStr.length
					let zStr = '(' + seachStr.substr(0, len - 1) + ')'
					let length = seachArr.filter((item) => item !== null).length
					if (this.formData.seach.zCity == 3) {
						length = length - 1
						// console.log("cityCode",length)
					}
					let n = Math.ceil(length * 0.5)
					let s = ""
					let reg = new RegExp(zStr, 'i')
					for (let i = 0; i < n; i++) {
						s += `${zStr}.*`
					}
					// console.log("+++++++",zStr,s)
					this.formData.seachZstr = s
				}
				db.collection("uni-id-users").where("_id == $env.uid").update(this.formData)
					.then(res => {
						uni.showToast({
							title: "奔向幸福中...",
							icon: 'none'
						})
						this.updateUserInfo()
						setTimeout(() => {
							uni.switchTab({
								url: "/pages/list/index"
							})
						}, 500)
						
					})
			},
		}
	}
</script>

<style scoped lang="scss">
	// view {
	// 	display: flex;
	// 	box-sizing: border-box;
	// 	// flex-direction: column;
	// }

	.warp {
		padding-bottom: 20px;
	}

	.setAvatar {
		display: flex;
		justify-content: flex-end;
	}

	// .item {
	// 	flex: 1;
	// 	flex-direction: row;
	// 	justify-content: space-between;
	// 	align-items: center;
	// }

	.uni-input {
		display: flex;
		align-items: center;
		height: 36px;
	}

	.btn {
		display: flex;
		justify-content: center;
	}

	.item {
		width: 100%;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.genderBox {
		display: flex;
		justify-content: space-between;
		width: 100%;
		font-size: 14px;
		color: #3b4144;
		overflow: hidden;
	}
</style>